import uniRequest from 'uni-request';
import {BASICINFO} from '@/common/config/index.js'
let url = '' ;
uniRequest.defaults.baseURL = BASICINFO.requestUrl;
uniRequest.defaults.timeout = 10000;
// uniRequest.defaults.headers.common['Authorization'] = 'Bearer '+uni.getStorageSync('token')
uniRequest.defaults.headers.post['Content-Type'] = 'application/json';
//HTTPrequest拦截
uniRequest.interceptors.request.use(config => {
	url=config.url
	// uni.showLoading({
	// 	title: 'loading',
	// 	mask:true
	// });
  //headers中配置serialize为true开启序列化
 //  wx.setStorage({
 //  	key: 'token',
 //  	data:{
	// 	access_token:1
	// },
 //  	success: function() {
 //  		// console.log('存储成功');
 //  	}
 //  });
  var value = wx.getStorageSync('token');
  if(config.url != '/api/app/login'){
	  console.log(value.access_token)
	  var value = wx.getStorageSync('token');
	  config.headers["Authorization"] = 'Bearer '+value.access_token;
    config.headers.Authorization = 'Bearer '+value.access_token
		// config.headers['Blade-Auth'] = value.access_token
  }
  
  //处理uni-request将数组转为对象的bug
  if(typeof config.data === 'string') config.data = JSON.parse(config.data)
  
  return config
}, error => {
  return Promise.reject(error)
});
//HTTPresponse拦截
uniRequest.interceptors.response.use(res => {
	if(res.data.code == 200||res.data.status=='00000'||res.data.status=='A0404'){
		return res.data;
	}else if(res.data.code == 401){
		if(url=='/api/AppNewsPrice/materialDetailedPrice'){
			uni.redirectTo({
				url:'/pages/login/login?showbacks=backs'
			})
		}else{
			uni.redirectTo({
				url:'/pages/login/login'
			})
		}
	}else{
		uni.showToast({
			title:res.data.msg?res.data.msg:'未知错误',
			icon:'error'
		})
	}
  
}, error => {
  return Promise.reject(new Error(error));
});
export default uniRequest